import React, { Component } from 'react';
import {
	StyleSheet,
	Text,
	View,
	Image,
	TouchableOpacity,
	DeviceEventEmitter,
	SectionList,
	ScrollView,
	PixelRatio
} from "react-native";
import request from './request';
import { style } from '../../theme/style';
import { GLOBAL } from '../../config/global';
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { Common } from '../../component/common/Common';

const scale = GLOBAL.SCALE;
export class ReportCollectList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { params } = navigation.state;

		return {
			title: params ? params.title : '收藏列表',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerTintColor: style.color.white,
			headerStyle: {
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				textAlign: 'center',
			}
		}
	}

	constructor(props) {
		super(props);
		this.state = {
			pageStatus: {
				status: 'loading'       //页面的状态  loading-请求中  data-数据返回 empty-数据为空 error-返回错误
			},
			imgDefault: false,
			rptList: []
		}
	}

	componentWillMount () {
		this._getReportList();
	}

	componentWillUnmount () {
		DeviceEventEmitter.emit('ChangeUI');
	}

	//点击收藏、取消收藏
	async _collectReport (id) {
		const collectResult = await request.collect(id);
		if (collectResult) {
			this._getReportList();
		}
	}

	//刷新
	async _getReportList () {
		const reportsList = await request.getReportList();
		if (reportsList) {
			this._setPageState(reportsList);
		} else {
			this.setState({
				pageStatus: {
					status: 'error',
					errorText: '请求数据异常~',
					onErrorPress: () => {
						this.setState({
							pageStatus: {
								status: 'loading',
							}
						});
						this._getReportList();
					}
				}
			});
		}
	}

	_setPageState (reports) {
		let rptList = [];
		if (reports.length && reports.length > 0) {
			this.setState({
				pageStatus: {
					status: 'data',
				},
				rptList: reports
			})
		} else {
			this.setState({
				pageStatus: {
					status: 'empty',
					emptyText: '还没有报表呢~',
					emptyBtnText: '返回',
					onEmptyPress: () => {
						this.props.navigation.goBack()
					}
				}
			});
		}
	}

	_cell (data) {
		const defaultImg = require('../../imgs/report/Group5.png');
		const sectionItem = data.item;
		return (
			<View style={styles.item}>
				<Image style={styles.left}
					source={sectionItem.iconUrl ? (imgDefault ? defaultImg : sectionItem.iconUrl) : defaultImg}
					onError={(e) => {
						this.setState({ imgDefault: true })
					}} />
				<Text style={styles.content}>{sectionItem.rptName}</Text>
				<TouchableOpacity style={[styles.right, { borderColor: sectionItem.attentionFlag === 1 ? style.color.themeColor : "#e4e4e4" }]}
					activeOpacity={0.5} onPress={() => {
						this._collectReport(sectionItem.rptId)
					}}>
					<Text style={{ color: sectionItem.attentionFlag === 1 ? style.color.themeColor : "#404040" }}>{sectionItem.attentionFlag === 1 ? "取消收藏" : "收藏"}</Text>
				</TouchableOpacity>
			</View>
		)
	}

	_header (header) {
		return (
			<View>
				<Text style={styles.title}>{header.section.name}</Text>
			</View>
		)
	}

	render () {
		const { pageStatus, rptList } = this.state;
		const defaultImg = require('../../imgs/report/Group5.png');
		const sections = [];
		if (rptList.length) {
			for (let i = 0; i < rptList.length; i++) {
				let datas = [];
				if (rptList[i].rptDeployVOList && rptList[i].rptDeployVOList.length > 0) {
					for (let j = 0; j < rptList[i].rptDeployVOList.length; j++) {
						datas.push(
							{
								iconUrl: rptList[i].rptDeployVOList[j].iconUrl,
								rptId: rptList[i].rptDeployVOList[j].rptId,
								rptName: rptList[i].rptDeployVOList[j].rptName,
								attentionFlag: rptList[i].rptDeployVOList[j].attentionFlag,
							}
						)
					}
					sections.push({ name: rptList[i].rptTypeVO.typeName, data: datas });
				}
			}
		}

		return (
			<ScrollView>
				<View style={styles.container}>
					<View style={styles.list}>
						{
							sections.length && sections.length > 0 ?
								(<SectionList sections={sections}//数据源
									renderItem={this._cell.bind(this)}//cell绑定时间创建cell
									keyExtractor={(item, index) => index}//去除警告
									renderSectionHeader={this._header.bind(this)}//Header绑定时间创建表头
									scrollEnabled={true}//默认是true，false禁止滚动
									refreshing={false}
									onRefresh={() => { this._getReportList.bind(this) }}
								/>
								) : (<PageStatusIndex {...pageStatus} />)   //页面状态
						}
					</View>
				</View>
			</ScrollView>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1
	},
	title: {
		fontSize: 12 * scale,
		color: '#4B4B4B',
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		paddingLeft: 17 * scale,
		paddingRight: 17 * scale,
	},
	list: {
		position: 'relative'
	},
	item: {
		flexDirection: 'row',
		alignItems: 'center',
		backgroundColor: '#fff',
		paddingTop: 17 * scale,
		paddingBottom: 17 * scale,
		paddingLeft: 22 * scale,
		paddingRight: 22 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#e4e4e4'
	},
	left: {
		marginRight: 17 * scale,
	},
	content: {
		flex: 1,
		fontSize: 14 * scale,
		color: '#404040'
	},
	right: {
		// width: 36 * scale,
		paddingTop: 4 * scale,
		paddingBottom: 4 * scale,
		paddingLeft: 20 * scale,
		paddingRight: 20 * scale,
		borderWidth: 1,
		borderStyle: 'solid',
		borderColor: '#e4e4e4',
		borderRadius: 5
	}
})